<!--  -->
<template>
  <div class="main">
    <!-- <PageHeaderText :text="'发布正式运单'"></PageHeaderText> -->

    <div class="container">
      <div class="item">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="货主公司" prop="company" style="width: 100%">
            <el-select
              filterable 
              v-model="form.company"
              placeholder="请选择货主公司"
              @change="(e) => selectChange(e, 'company')"
            >
              <el-option
                v-for="(item, index) in companyList"
                :key="index"
                :label="item.company_name"
                :value="index"
              ></el-option>
            </el-select>
            <!-- <el-button @click.prevent="goPage('/oftenAddress/page')">添加新地址</el-button> -->
            <!-- <el-button @click.prevent="dialogVisible = true">添加新地址</el-button> -->
          </el-form-item>
          <el-form-item label="出发地" prop="from_address_id" required>
            <el-select
              v-model="srartArd"
              placeholder="请选择出发地"
              filterable
              @change="(e) => selectChange(e, 'start')"
            >
              <el-option
                v-for="(item, index) in adressList"
                :key="index"
                :label="item.province + item.city + item.area + '-' + item.detail"
                :value="index"
              ></el-option>
            </el-select>
            <!-- <el-button @click.prevent="goPage('/oftenAddress/page')">添加新地址</el-button> -->
            <el-button @click.prevent="dialogVisible = true">添加新地址</el-button>
          </el-form-item>
          <el-form-item label="卸货地" prop="to_address_id" required>
            <el-select
              v-model="endArd"
              placeholder="请选择活动区域"
              filterable
              @change="(e) => selectChange(e, 'end')"
            >
              <el-option
                v-for="(item, index) in adressList"
                :key="index"
                :label="item.province + item.city + item.area + '-' + item.detail"
                :value="index"
              ></el-option>
            </el-select>
            <!-- <el-button @click.prevent="goPage('/oftenAddress/page')">添加新地址</el-button> -->
            <el-button @click.prevent="dialogVisible = true">添加新地址</el-button>
          </el-form-item>
          <el-form-item label="所需车型" prop="models">
            <el-select v-model="form.models" placeholder="--请选择车辆类型--">
              <el-option
                v-for="(item, index) in publicList.carType"
                :key="index"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
            <!-- <el-button @click.prevent="removeDomain(domain)">添加新地址</el-button> -->
          </el-form-item>
          <el-form-item label="所需车长" prop="chechang">
            <el-select v-model="form.chechang" placeholder="--请选择车长--">
              <el-option
                v-for="(item, index) in publicList.carLong"
                :key="index"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="指派司机">
            <el-select v-model="form.driver" placeholder="--点击选择司机(可以不选择)--" disabled>
              <el-option label="区域一" value="shanghai"></el-option>
              <el-option label="区域二" value="beijing"></el-option>
            </el-select>
            <!-- <el-button @click.prevent="removeDomain(domain)">添加新地址</el-button> -->
          </el-form-item>
          <el-form-item label="货物类型" prop="type">
            <el-select v-model="form.type" placeholder="--请选择货物类型--">
              <el-option
                v-for="(item, index) in publicList.goodsType"
                :key="index"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="发货方姓名" prop="name">
            <el-input class="custom-input" type="text" v-model="form.name" placeholder="请输入发货方姓名"></el-input>
          </el-form-item>
          <el-form-item label="发货方电话" prop="phone">
            <el-input class="custom-input" type="text" v-model="form.phone" placeholder="请输入发货方电话"></el-input>
          </el-form-item>
          <el-form-item label="收货方姓名" prop="con_name">
            <el-input class="custom-input" placeholder="请输入收货方姓名" type="text" v-model="form.con_name"></el-input>
          </el-form-item>

          <el-form-item label="收货方电话" prop="con_phone">
            <el-input class="custom-input" placeholder="请输入收货方电话" type="text" v-model="form.con_phone"></el-input>
          </el-form-item>-->

          <!-- <el-form-item label="发货日期">
            <el-col>
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="form.date1"
                style="width: 100%;"
              ></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="截止日期">
            <el-col>
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="form.date1"
                style="width: 100%;"
              ></el-date-picker>
            </el-col>
          </el-form-item>-->
          <el-form-item label="货物名称" prop="goods">
            <el-input class="custom-input" type="text" v-model="form.goods" placeholder="请输入货物名称"></el-input>
          </el-form-item>

          <el-form-item label="货物重量" prop="weight">
            <el-input class="custom-input" placeholder="单位：吨" type="number" v-model="form.weight">
              <template slot="append">
                <span style="font-weight: 600;font-size: 14px;color: #555;">吨</span>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="运费单价" prop="huo_price">
            <el-input
              class="custom-input"
              placeholder="单位：元/吨"
              type="number"
              v-model="form.huo_price"
            >
              <template slot="append">
                <span style="font-weight: 600;font-size: 14px;color: #555;">元/吨</span>
              </template>
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="备注信息">
            <el-input class="custom-input" placeholder="请输入备注信息（简单清楚即可）" type="text" v-model="form.remark"></el-input>
          </el-form-item>-->
          <el-form-item label="选择车队长">
            <el-select v-model="form.assign_user_id" filterable placeholder="--请选择车队长--">
              <el-option
                v-for="(item, index) in fleetList"
                :key="index"
                :label="item.person_name + '-' + item.tel"
                :value="item.owner_id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="允许亏吨数" class="flex" :required="!(form.is_road == 0)">
            <el-input-number
              :disabled="(form.is_road === 0)"
              v-model="form.road_consumption"
              controls-position="right"
              :min="0"
              :controls="false"
              :precision="2"
              :step="0.01"
            ></el-input-number>
            <div class="unit">吨</div>
          </el-form-item>
          <el-form-item label="是否超载" class="road_consumption">
            <el-switch v-model="form.is_overload" 
            active-text="超载" 
            :active-value="1" 
            inactive-text="不超载"
            :inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="发货方式" class="road_consumption">
            <el-switch v-model="form.is_carload" 
            active-text="整车" 
            :active-value="1" 
            inactive-text="散货"
            :inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="整车价格" class="flex" required v-if="form.is_carload">
            <el-input-number
              v-model="form.car_price"
              controls-position="right"
              :min="0"
              placeholder="请填写整车单价"
              :controls="false"
            ></el-input-number>
            <div class="unit">元/吨</div>
          </el-form-item>
          <el-form-item label="启用路耗" class="road_consumption">
            <el-switch v-model="form.is_road" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="运输成本" class="road_consumption">
            <el-switch v-model="form.is_cost" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="货物单价" class="flex" required v-if="form.is_road">
            <el-input-number
              v-model="form.goods_price"
              controls-position="right"
              :min="0"
              placeholder="请填写货物单价"
              :controls="false"
            ></el-input-number>
            <div class="unit">元/吨</div>
          </el-form-item>
          <el-form-item label="装车费" class="flex" required v-if="form.is_cost">
            <el-input-number
              v-model="form.loading_charge"
              controls-position="right"
              :min="0"
              placeholder="请填写装车费"
              :controls="false"
            ></el-input-number>
            <div class="unit">元</div>
          </el-form-item>
          <el-form-item label="卸车费" class="flex" required v-if="form.is_cost">
            <el-input-number
              v-model="form.unloading_charge"
              controls-position="right"
              :min="0"
              placeholder="请填写卸车费费"
              :controls="false"
            ></el-input-number>
            <div class="unit">元</div>
          </el-form-item>
          <el-form-item label="信息费" class="flex" required v-if="form.is_cost">
            <el-input-number
              v-model="form.information_cost"
              controls-position="right"
              :min="0"
              placeholder="请填写信息费"
              :controls="false"
            ></el-input-number>
            <div class="unit">元</div>
          </el-form-item>
          <el-form-item label="保险费" class="flex" required v-if="form.is_cost">
            <el-input-number
              v-model="form.insurance_expense"
              controls-position="right"
              :min="0"
              placeholder="请填写保险费"
              :controls="false"
            ></el-input-number>
            <div class="unit">元</div>
          </el-form-item>
          <el-form-item label="押金" class="flex" required v-if="form.is_cost">
            <el-input-number
              v-model="form.deposit_charge"
              controls-position="right"
              :min="0"
              placeholder="请填写押金"
              :controls="false"
            ></el-input-number>
            <div class="unit">元</div>
          </el-form-item>


          <el-form-item label v-if="form.is_road"></el-form-item>
          <el-form-item label="预估距离">
            <span style="font-size: 20px;color: red;">{{ form.distance }}km</span>
          </el-form-item>
          <el-form-item label="货物图片" style="width: 100%;">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="getHeader()"
              :show-file-list="false"
              :drag="true"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.hpic" :src="form.hpic" class="avatar" />
              <div v-else>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处,或
                  <em>点击上传</em>
                </div>
              </div>
            </el-upload>
            <p style="color: #f00;transform: translateX(20px);">选填</p>
          </el-form-item>

          <!-- <el-form-item label="生成二维码" class="radio-item" required>
            <el-radio disabled v-model="form.qrcode" label="1">是</el-radio>
            <el-radio disabled v-model="form.qrcode" label="2">否</el-radio>
          </el-form-item>-->



          <div class="tool">
            <!-- <el-form-item label class="radio-item" style="width: auto;">
              <el-radio v-model="sign" label="1">
                为确保三方利益请签订
                <span style="color: #409EFF;" @click="showContract">《运输管理合同》</span>
              </el-radio>
            </el-form-item>-->
            <el-form-item style="width: auto;">
              <el-button
                class="sureBtn"
                type="primary"
                v-loading="createLoading"
                :disabled="createLoading"
                @click="onSubmit('form')"
              >立即创建</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>

    <el-dialog title="添加地址" :visible.sync="dialogVisible" width="50%" :close-on-click-modal="false">
      <AddressDialog v-if="dialogVisible" :companyList="companyList" @addSuccess="addSuccess"></AddressDialog>
    </el-dialog>
  </div>
</template>

<script>
import { getAllCompany,getCompanyAddress, releaseWayNewBill,fleetList } from "@/api/businessUser/release";
import { publicList, uploadUrl, getHeader } from "@/utils/tool";
import AddressDialog from "./components/AddressDialog";
import Big from "big.js";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    AddressDialog
  },
  data() {
    var checkRoadConsumption = (rule, value, callback) => {
      console.log(rule, value, callback);
      if (value == 0) {
        setTimeout(() => {
          this.$message.info(
            "您好！如果允许亏吨数为0，则以吨差重量*货物单价作为运费扣款标准"
          );
        });
      }
      callback();
    };
    //这里存放数据
    return {
      uploadUrl,
      getHeader,
      adressList: [],
      publicList: publicList(),
      fleetList: [], //车队长列表
      sign: "0",
      rules: {
        from_address_id: {
          required: true,
          message: "请选择出发地",
          trigger: "change"
        },
        to_address_id: {
          required: true,
          message: "请选择卸货地",
          trigger: "change"
        },
        models: {
          required: true,
          message: "请选择所需车型",
          trigger: "change"
        },
        company:{ required: true, message: "请选择货主公司", trigger: "change" },
        chechang: { required: true, message: "请选择车长", trigger: "change" },
        type: { required: true, message: "请选择货物类型", trigger: "change" },
        goods: { required: true, message: "请输入货物名称", trigger: "blur" },
        weight: { required: true, message: "请输入货物重量", trigger: "blur" },
        huo_price: {
          required: true,
          message: "请输入运费单价",
          trigger: "blur"
        }
        // road_consumption: [
        //   { validator: checkRoadConsumption, trigger: 'blur' },
        //   { required: true, message: "允许亏吨数不能为空", trigger: "blur" },
        // ]
      },
      srartArd: "",
      endArd: "",
      companyList:[],//公司列表
      form: {
        owner_id:'',//货主id
        company:'',//公司名称
        chechang: "不限", //车长
        danwei: "吨", //货物单位
        from_address_id: "", //出发地地址id
        to_address_id: "", //目的地地址id
        distance: 0, //预估距离
        goods: "", //货物名称
        goods_price: undefined, //货物单价
        huo_price: "", //运费单价

        models: "半挂", //所需车型
        payment_tax: 0,
        weight: "", //货物重量
        qrcode: 1, //生成二维码
        hpic: "", //货物图片

        type: "", //货物类型
        assign_user_id: "",
        is_road: 0, //是否开启路耗
        road_consumption: 0,

        is_cost: 0, //是否开启运输成本
        loading_charge: 0, //装车费用
        unloading_charge: 0, //卸车费用
        insurance_expense: 0, //保险费用
        information_cost: 0, //信息费用
        deposit_charge: 0, //押金费用

        is_overload:0,//0不超载 1超载
        is_carload:0,//0散货 1整车
        car_price:0,//包车价格
      },
      imageUrl: "",
      dialogVisible: false,

      roadDetail: {
        //路耗详情
      },

      createLoading: false //立即创建加载中
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    "form.from_address_id": {
      handler(newV, oldV) {
        if (newV) {
          if (this.form.to_address_id) {
            const res_start = this.adressList.find(item => item.id === newV);
            const res_end = this.adressList.find(
              item => item.id === this.form.to_address_id
            );
            let start = new TMap.LatLng(
                Number(res_start.lat),
                Number(res_start.lng)
              ),
              end = new TMap.LatLng(Number(res_end.lat), Number(res_end.lng));
            let path = [start, end];
            let distance = (
              Math.floor(TMap.geometry.computeDistance(path)) / 1000
            ).toFixed(2);
            this.form.distance = distance;
          }
        }
      }
    },
    "form.to_address_id": {
      handler(newV, oldV) {
        if (newV) {
          if (this.form.from_address_id) {
            const res_start = this.adressList.find(
              item => item.id === this.form.from_address_id
            );
            const res_end = this.adressList.find(item => item.id === newV);
            let start = new TMap.LatLng(
                Number(res_start.lat),
                Number(res_start.lng)
              ),
              end = new TMap.LatLng(Number(res_end.lat), Number(res_end.lng));
            let path = [start, end];
            let distance = (
              Math.floor(TMap.geometry.computeDistance(path)) / 1000
            ).toFixed(2);
            this.form.distance = distance;
          }
        }
      }
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // this.getAddress();
    this.initial();
  },
  //方法集合
  methods: {
    async initial(){
        let result = await getAllCompany();
        if(result.code == 200){
            this.companyList = result.data;
        }
        
        let result2 = await fleetList();
        if(result2.code == 200){
            this.fleetList = result2.data;
        }
    },
    goPage(path) {
      this.$router.push(path);
    },
    selectChange(val, type) {
      if (type == "start") {
        this.form.from_address_id = this.adressList[val].id;
      }
      if (type == "end") {
        this.form.to_address_id = this.adressList[val].id;
      }
      if(type == 'company'){
        this.form.owner_id = this.companyList[val].owner_id;
        this.form.company = this.companyList[val].company_name;

        //更新收货地址接口
        this.form.from_address_id = '';
        this.form.to_address_id = '';
        this.srartArd = "";
        this.endArd = "";
        this.adressList = [];
        this.getAddress();
      }
    },
    getTimestampNextYear() {
      let currentTimestamp = Date.now();
      const currentDate = new Date(currentTimestamp);
      currentDate.setFullYear(currentDate.getFullYear() + 1);
      return Math.floor(currentDate.getTime() / 1000);
    },
    onSubmit(formName) {
      // if (this.sign != "1") {
      //   this.$message.error("请先同意签订《运输管理合同》");
      //   return;
      // }
      // console.log(this.form, "this.form");
      // return;
      this.$refs[formName].validate(valid => {
        if (this.form.is_road === 1 && this.form.road_consumption == null) {
          this.$message.error("请输入允许亏吨数");
          return false;
        }
        if (
          this.form.is_road === 1 &&
          !this.form.goods_price &&
          !(this.form.goods_price > 0)
        ) {
          this.$message.error("请填写货物单价");
          return false;
        }

        if (valid) {
          if (!this.form.weight || !(this.form.weight > 0)) {
            this.$message.error("请填写正确的货物重量!");
            return;
          }
          this.createLoading = true;
          delete this.form.driver;
          // this.form.price = this.form.weight * this.form.huo_price;
          let weight = new Big(this.form.weight);
          let huo_price = new Big(this.form.huo_price);
          this.form.price = weight.times(huo_price).toString();
          releaseWayNewBill({
            ...this.form,
            assign_user_id: 0
          }).then(res => {
            // console.log("res", res);
            this.createLoading = false;
            if (res.code == 200) {
              this.$message({
                message: "发布成功",
                type: "success"
              });
              this.$router.push("/waybillmanagement/list");
            }
          });
        } else {
          return false;
        }
      });
    },
    async getAddress() {
      let res = await getCompanyAddress({
        owner_id:this.form.owner_id,
        company:this.form.company,
        type:1
      });
      if (res.code == 200) {
        this.adressList = res.data.data;
      }

    },
    showContract() {
      console.log(123);
    },
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.form.hpic = res.data.url;
      }
    },
    beforeAvatarUpload(file) {
      return true;
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    addSuccess() {
      //添加地址成功的回调
      this.dialogVisible = false;
      this.getAddress();
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {}
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.main {
  width: 100%;
  min-height: calc(100vh - 50px - 20px);
  background-color: #fff;
  border-radius: 10px;
  padding-top: 10px;
  overflow: auto;

  .container {
    display: flex;
    width: 100%;
    padding: 0 10%;

    .item {
      width: 100%;

      ::v-deep .el-form {
        display: flex;
        flex-wrap: wrap;

        .flex {
          .el-form-item__content {
            display: flex;
          }
        }

        .road_consumption {
          .el-form-item__content {
            height: 100%;
            align-items: center;
          }
        }

        .unit {
          text-align: center;
          width: 80px;
          height: 40px;
          padding: 0 20px;
          transform: scaleX(1.01);
          background-color: #f5f7fa;
          color: #999;
          border: 1px solid #dcdfe6;
          border-top-right-radius: 5px;
          border-bottom-right-radius: 5px;
        }

        .el-input-number {
          width: 100%;

          .el-input__inner {
            text-align: left;
            padding-right: 30px;
          }
        }

        .el-form-item {
          width: 50%;
        }

        .tool {
          width: 100%;
          display: flex;
          flex-direction: column;
          align-items: center;

          .sureBtn {
            width: 250px;
          }
        }
      }
    }
  }

  ::v-deep .el-form {
    min-width: 500px;
  }

  .radio-item {
    ::v-deep .el-form-item__content {
      height: 42px;
    }
  }

  ::v-deep .el-form-item__content {
    display: flex;

    .custom-input {
      width: 100%;
    }

    .el-select {
      width: 100%;
    }

    .el-input {
      width: 100%;
    }

    .el-button {
      margin-left: 20px;
      background-color: $theme-primary;
      color: #fff;
      border: none;
      // border-radius: 20px;
    }

    .el-radio {
      display: flex;
      align-items: center;
      height: 100%;
    }
  }
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

::v-deep .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

::v-deep .el-upload-dragger {
  width: 178px;
}
</style>